//
//  AppDelegate.m
//  Project_B
//
//  Created by 张闯的mac pro on 15/11/28.
//  Copyright © 2015年 张闯. All rights reserved.
//

#import "AppDelegate.h"
#import "FirstMainViewController.h"
#import "ThirdlubViewController.h"
#import "FifthVideoViewController.h"
#import "TCSpecialTopicViewController.h"
#import "TCEquipmentViewController.h"
#import "MenuViewController.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "UMSocial.h"
#import "APService.h"
#import <AVFoundation/AVFoundation.h>
#import <EaseMob.h>
#import "ZCSTKPlayer.h"
#import "RESideMenu.h"
#import "UMSocialWechatHandler.h"

@interface AppDelegate ()
@property (nonatomic, retain)UIViewController *leaderView;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    //
    
    //音乐后台播放
    NSError* error;
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
    [[AVAudioSession sharedInstance] setActive:YES error:&error];
    
    
    
    //告诉系统，我们要接受远程控制事件
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
    
    
    [UMSocialData setAppKey:@"56396942e0f55a01aa00062c"];
    //设置微信AppId，设置分享url，默认使用友盟的网址
    //[UMSocialWechatHandler setWXAppId:@"wxdc1e388c3822c80b" appSecret:@"56396942e0f55a01aa00062c" url:@"http://www.umeng.com/social"];
    [UMSocialConfig hiddenNotInstallPlatforms:@[UMShareToQzone]];
    
    //注册环信
    [[EaseMob sharedInstance] registerSDKWithAppKey:@"18940033425#bproject" apnsCertName:@""];
    
    // Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                       UIUserNotificationTypeSound |
                                                       UIUserNotificationTypeAlert)
                                           categories:nil];
    } else {
        //categories 必须为nil
        [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                       UIRemoteNotificationTypeSound |
                                                       UIRemoteNotificationTypeAlert)
                                           categories:nil];
    }
    
    // Required
    [APService setupWithOption:launchOptions];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *result = [user objectForKey:@"firstTime"];
    if (result != nil ) {
        [self creatTabBar];
    }
    else
    {
        [user setObject:@"LZT" forKey:@"firstTime"];
        [self leader];
    }
    return YES;
}
- (void)creatTabBar
{
    FirstMainViewController *firstVC = [[FirstMainViewController alloc] init];
    firstVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"精选" image:[UIImage imageNamed:@"iconfont-jingxuan"] tag:100];
    UINavigationController *nv1 = [[UINavigationController alloc] initWithRootViewController:firstVC];
    
    TCSpecialTopicViewController *mainVC = [[TCSpecialTopicViewController alloc] init];
    UINavigationController *nv2 = [[UINavigationController alloc] initWithRootViewController:mainVC];
    nv2.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"专题" image:[UIImage imageNamed:@"iconfont-topic"] selectedImage:[UIImage imageNamed:@""]];
    
    TCEquipmentViewController *secVC = [[TCEquipmentViewController alloc]init];
    UINavigationController *nv4 = [[UINavigationController alloc]initWithRootViewController:secVC];
    nv4.tabBarItem = [[UITabBarItem alloc]initWithTitle:@"装备" image:[UIImage imageNamed:@"iconfont-leimutubiaohuwaiyongpin@3x"] selectedImage:[UIImage imageNamed:@""]];
    
    ThirdlubViewController *thirdVC = [[ThirdlubViewController alloc] init];
    thirdVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"俱乐部" image:[UIImage imageNamed:@"iconfont-julebu@3x"] tag:102];
    UINavigationController *nv3 = [[UINavigationController alloc] initWithRootViewController:thirdVC];
    
    
    FifthVideoViewController *fifVC = [[FifthVideoViewController alloc] init];
    fifVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"视听" image:[UIImage imageNamed:@"iconfont-icon@3x"] tag:104];
    UINavigationController *nv5 = [[UINavigationController alloc] initWithRootViewController:fifVC];
    
    
    self.tab = [[UITabBarController alloc] init];
    self.tab.viewControllers = @[nv1,nv2, nv3,nv4, nv5];
    self.tab.tabBar.tintColor = [UIColor colorWithRed:60.0 / 255 green:149.0 / 255 blue:58.0 / 255 alpha:1];
    
    //抽屉
    MenuViewController *leftMenu = [[MenuViewController alloc] init];
    RESideMenu *sideMenuViewController = [[RESideMenu alloc] initWithContentViewController:self.tab leftMenuViewController:leftMenu rightMenuViewController:nil];
    sideMenuViewController.backgroundImage = [UIImage imageNamed:@"22.png"];
    
    sideMenuViewController.menuPreferredStatusBarStyle = 1; // UIStatusBarStyleLightContent
    sideMenuViewController.contentViewShadowColor = [UIColor blackColor];


    sideMenuViewController.contentViewShadowOffset = CGSizeMake(200, 0);
    sideMenuViewController.contentViewShadowOpacity = 0.6;
    sideMenuViewController.contentViewShadowRadius = 12;
    sideMenuViewController.contentViewShadowEnabled = YES;
    
    
//    [self authenticateUser];
    

    sideMenuViewController.contentViewShadowOffset = CGSizeMake(0, 0);
    sideMenuViewController.contentViewShadowOpacity = 0.6;
    sideMenuViewController.contentViewShadowRadius = 12;
    sideMenuViewController.contentViewShadowEnabled = NO;




    self.window.rootViewController = sideMenuViewController;
}
- (void)leader
{
    self.leaderView = [[UIViewController alloc]init];
    UIImageView *image = [[UIImageView alloc]initWithFrame:self.leaderView.view.frame];
    [image setImage:[UIImage imageNamed:@"1"]];
    [self.leaderView.view addSubview:image];
    [NSTimer scheduledTimerWithTimeInterval:(0.05) target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
    UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(150, 500, 75, 40)];
    button.backgroundColor = [UIColor redColor];
    [button setTitle:@"哈哈" forState:UIControlStateNormal];
    [self.leaderView.view addSubview:button];
    [button setShowsTouchWhenHighlighted:YES];
    self.window.rootViewController = self.leaderView;
    [button addTarget:self action:@selector(creatTabBar) forControlEvents:UIControlEventTouchUpInside];
}
- (void)onTimer
{
    //创建图像视图对象
    UIImageView* flakeView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"3"]];
    int startX = round(random() % 375);
    int endX = round(random() % 375);
    double scale = 1 / round(random() % 1000) + 1.0;
    double speed = 1 / round(random() % 1000) + 1.0;
    flakeView.frame = CGRectMake(startX, -10.0, 25.0 * scale, 25.0 * scale);
    flakeView.alpha = 0.5;
    [self.leaderView.view addSubview:flakeView];
    [UIView beginAnimations:nil context:(__bridge void *)(flakeView)];
    [UIView setAnimationDuration:10 * speed];
    flakeView.frame = CGRectMake(endX, 667.0, 25.0 * scale, 25.0 * scale);
    [UIView commitAnimations];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    // Required
    [APService registerDeviceToken:deviceToken];
}


- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required
    [APService handleRemoteNotification:userInfo];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // IOS 7 Support Required
    [APService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
    //取消徽章
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[EaseMob sharedInstance] applicationDidEnterBackground:application];
    [application beginBackgroundTaskWithExpirationHandler:nil];
    [application beginReceivingRemoteControlEvents];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [[EaseMob sharedInstance] applicationWillEnterForeground:application];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [[EaseMob sharedInstance] applicationWillTerminate:application];
}

- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {
    
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        
        switch (receivedEvent.subtype) {
                
            case UIEventSubtypeRemoteControlPause:
//                [self playButtonPressed:playButton];
//                [self testing];
                [[ZCSTKPlayer shareInstance] pause];
                NSLog(@"play");
                break;
                
                
            case UIEventSubtypeRemoteControlPlay:
                //                [self playButtonPressed:playButton];
                //                [self testing];
//                [self];
                NSLog(@"play");
                break;
                
            case UIEventSubtypeRemoteControlPreviousTrack:
//                [self rewButtonReleased:(UIButton *)rewButton];
                NSLog(@"last");
                break;
                
            case UIEventSubtypeRemoteControlNextTrack:
//                [self ffwButtonReleased:(UIButton *)ffwButton];
                NSLog(@"next");
                break;
                
            default:
                break;  
        }  
    }  
}



@end
